/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BackupDlg.java
 *
 * Created on Jul 15, 2011, 3:03:43 PM
 */
package com.viweb.storemanager.ui.database;

import java.io.File;
import com.viweb.storemanager.core.CursorManager;
import com.viweb.storemanager.core.DateUtil;
import com.viweb.storemanager.core.OptionPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.swing.JFileChooser;
import javax.swing.Timer;
import javax.swing.JOptionPane;

/**
 *
 * @author qhvic
 */
public class BackupDlg extends javax.swing.JDialog {

    private final int ONE_SECOND = 1000;
    private Timer timer;
    private ProcessTask processTask;
    private File backupFolder;
    private boolean finish;

    /** Creates new form BackupDlg */
    public BackupDlg(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        this.processTask = new ProcessTask(1000);
        initComponents();
        this.txtFileName.setText("MyCafe_" + DateUtil.createUniqueFilename() + ".backup");
        initBackupProcess();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        fileChooser = new javax.swing.JFileChooser();
        lblFileName = new javax.swing.JLabel();
        lblStatus = new javax.swing.JLabel();
        txtFileName = new javax.swing.JTextField();
        btnSelect = new javax.swing.JButton();
        sep1 = new javax.swing.JSeparator();
        pbBackup = new javax.swing.JProgressBar();
        pnlControl = new javax.swing.JPanel();
        btnOK = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        lblFileName.setText("Tên tập tin:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
        getContentPane().add(lblFileName, gridBagConstraints);

        lblStatus.setText("Trạng thái:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
        getContentPane().add(lblStatus, gridBagConstraints);

        txtFileName.setMaximumSize(new java.awt.Dimension(6, 22));
        txtFileName.setMinimumSize(new java.awt.Dimension(6, 22));
        txtFileName.setPreferredSize(new java.awt.Dimension(6, 22));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
        getContentPane().add(txtFileName, gridBagConstraints);

        btnSelect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/viweb/storemanager/imgae/selection.png"))); // NOI18N
        btnSelect.setMaximumSize(new java.awt.Dimension(40, 25));
        btnSelect.setMinimumSize(new java.awt.Dimension(40, 25));
        btnSelect.setPreferredSize(new java.awt.Dimension(40, 25));
        btnSelect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
        getContentPane().add(btnSelect, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 5);
        getContentPane().add(sep1, gridBagConstraints);

        pbBackup.setMinimumSize(new java.awt.Dimension(350, 20));
        pbBackup.setPreferredSize(new java.awt.Dimension(350, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(15, 5, 0, 5);
        getContentPane().add(pbBackup, gridBagConstraints);

        btnOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/viweb/storemanager/imgae/artsbuilderexecute.png"))); // NOI18N
        btnOK.setText("Bắt đầu");
        btnOK.setToolTipText("Bắt đầu thực hiện sao lưu dữ liệu");
        btnOK.setMaximumSize(new java.awt.Dimension(90, 26));
        btnOK.setMinimumSize(new java.awt.Dimension(90, 26));
        btnOK.setPreferredSize(new java.awt.Dimension(90, 26));
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });
        pnlControl.add(btnOK);

        btnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/viweb/storemanager/imgae/media_stop_red.png"))); // NOI18N
        btnCancel.setText("Đóng");
        btnCancel.setToolTipText("Đóng cửa sổ sao lưu dữ liệu");
        btnCancel.setMaximumSize(new java.awt.Dimension(90, 26));
        btnCancel.setMinimumSize(new java.awt.Dimension(90, 26));
        btnCancel.setPreferredSize(new java.awt.Dimension(90, 26));
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });
        pnlControl.add(btnCancel);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(pnlControl, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
        // TODO add your handling code here:
        if (finish) {
            this.dispose();
        }

        if (backupFolder == null) {
            OptionPane.show(JOptionPane.getFrameForComponent(BackupDlg.this),
                    "Chưa chọn thư mục chứa tập tin sao lưu!", "Thông báo");
            return;
        }

        txtFileName.setEditable(false);
        btnSelect.setEnabled(false);
        btnCancel.setEnabled(false);
        btnOK.setEnabled(false);
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        CursorManager.setWaitCursor(this);
        processTask.go();
        timer.start();

        Runnable processRunnable = new Runnable() {

            public void run() {
                // <editor-fold defaultstate="collapsed" desc=" Backup Database Process ">
                try {
                    String srcFileName = System.getProperty("user.dir") + "\\db\\my_cafe.mdb";
                    String dstFileName = backupFolder.getAbsolutePath() + "\\" + txtFileName.getText().trim();
                    FileInputStream in = new FileInputStream(new File(srcFileName));
                    FileOutputStream out = new FileOutputStream(new File(dstFileName));

                    // Transfer bytes from in to out
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    in.close();
                    out.close();
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }
                // </editor-fold>
            }
        };

        Thread processThread = new Thread(processRunnable);
        processThread.start();
    }//GEN-LAST:event_btnOKActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectActionPerformed
        // TODO add your handling code here:
        this.fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int open = this.fileChooser.showOpenDialog(this);
        if (open == JFileChooser.APPROVE_OPTION) {
            this.backupFolder = this.fileChooser.getSelectedFile();
        } else {
            this.backupFolder = null;
        }
    }//GEN-LAST:event_btnSelectActionPerformed

    private void initBackupProcess() {
        //Create a timer.
        timer = new Timer(ONE_SECOND, new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                pbBackup.setValue(processTask.getCurrent());

                if (processTask.isDone()) {
                    timer.stop();
                    btnOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/mycafe/images/ok.png"))); // NOI18N
                    btnOK.setText("Kết thúc");
                    btnOK.setToolTipText("Sao lưu dữ liệu thành công!");
                    btnOK.setEnabled(true);
                    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
                    finish = true;
                    CursorManager.setDefaultCursor(BackupDlg.this);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOK;
    private javax.swing.JButton btnSelect;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JLabel lblFileName;
    private javax.swing.JLabel lblStatus;
    private javax.swing.JProgressBar pbBackup;
    private javax.swing.JPanel pnlControl;
    private javax.swing.JSeparator sep1;
    private javax.swing.JTextField txtFileName;
    // End of variables declaration//GEN-END:variables
}
